package me.zhengjie.common.utils.batchsave.callable

import me.zhengjie.logging.slf4j.*
import me.zhengjie.common.utils.batchsave.vo.CallableResultVo
import me.zhengjie.common.utils.EntityManagerHelper
import jakarta.persistence.EntityTransaction
import jakarta.persistence.EntityManager
import org.springframework.transaction.annotation.Transactional

import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
open class PartSaveCallable<S>(private val lists: List<S>, cdl: CountDownLatch, isSave: Boolean) : Callable<Any?> {
    private val cdl: CountDownLatch
    private val isSave: Boolean

    init {
        this.cdl = cdl
        this.isSave = isSave
    }

    @Transactional
    override fun call(): CallableResultVo<S>? {
        val result: CallableResultVo<S> = CallableResultVo()
        val resultList: MutableList<S> = ArrayList()
        val su = if (isSave) "插入" else "更新"
       logInfo("--------------线程" + Thread.currentThread() + "开始执行" + su + "操作!，当前cdl is -------：" + cdl.getCount() + " -----------------------------")
        //当前线程em
        val em: EntityManager = EntityManagerHelper.entityManager!!
        val entityTransaction: EntityTransaction = em.getTransaction()
        try {
            logInfo("-------------current EntityManager is ：{$em} -------------")
            EntityManagerHelper.beginTransaction()
            //log.info("-------------list Size is ：{} -------------",lists.size());
            for (s in lists) {
                if (isSave) {
                    em.persist(s)
                } else {
                    em.merge(s)
                }
                resultList.add(s)
            }
            EntityManagerHelper.commitTransaction()
            EntityManagerHelper.closeEntityManager()
            result.result=resultList
            logInfo("-------------线程" + Thread.currentThread() + su + "完成，当前cdl(--) is -------：" + cdl.getCount() + " -------------")
            cdl.countDown()
        } catch (e: RuntimeException) {
            if (entityTransaction.isActive()) {
                entityTransaction.rollback()
            }
            logError("发生错误 :{${e.message}}")
        }
        return result
    }
}